<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import MEcharts from '/@/components/MEcharts/MEcharts.vue';
  const props = defineProps({
    data: { type: Object as () => any, required: true },
  });

  const chartRef = ref();

  const option = ref<any>({
    tooltip: {
      trigger: 'item',
      position: function (point: any, params: any, dom: any, rect: any, size: any) {
        return [point[0] + 10, point[1]]; // 将提示框向右偏移10像素
      },
    },
    series: [
      {
        animationDelay() {
          return Math.random() * 400;
        },
        animationEasing: 'exponentialInOut',
        animationType: 'scale',
        center: ['50%', '50%'],
        color: ['#5ab1ef', '#8e7cc3', '#b6a2de', '#67e0e3', '#2ec7c9'],
        data: [
          { name: '', value: 0 },
          // { name: '品规一级', value: 500 },
          // { name: '品规二级', value: 310 },
          // { name: '品规三级', value: 274 },
          // { name: '品规四级', value: 400 },
        ].sort((a, b) => {
          return a.value - b.value;
        }),
        name: '损失重量',
        radius: '80%',
        roseType: 'radius',
        type: 'pie',
      },
    ],
  });

  const myChart = ref<InstanceType<typeof MEcharts>>();
  const updateChart = () => {
    option.value.series[0].data = props.data[0] ?? [];
    myChart.value?.resizeHandler();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      updateChart();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
  });

  watch(
    () => [props.data],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container">
    <m-echarts :option="option"></m-echarts>
  </div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
